<?php
/* 
 * Copyright (c) 2011 Antoine d'Otreppe de Bouvette
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/**
 * A container that can be used to store data in session 
 */
class SessionContainer {
    /**
     * The key used by this container in $_SESSION
     * @var string
     */
    private $key;
    
    /**
     * @param string $key The key to be used by this container in $_SESSION
     */
    public function __construct($key) {
        $this->key = $key;
    }
    
    /**
     * Returns true if the attribute has been defined and is not null.
     * 
     * @param string $name
     * @return boolean true if $name is set and not null in this container
     */
    public function __isset($name) {
        return $this->$name !== null;
    }
    
    /**
     * Unset the attribute for this container.
     * 
     * @param string $name
     * @return void
     */
    public function __unset($name) {
        $this->$name = null;
    }
    
    /**
     * Returns the value set for this attribute, or null if none was set.
     * 
     * @param string $name
     * @return mixed
     */
    public function __get($name) {
        if (!array_key_exists($this->key, $_SESSION)) {
            $_SESSION[$this->key] = array();
        }
        
        return array_get($_SESSION[$this->key], $name);
    }
    
    /**
     * Stores an attribute in this container.
     * 
     * @param string $name
     * @param mixed $value 
     * @return void
     */
    public function __set($name, $value) {
        if (!array_key_exists($this->key, $_SESSION)) {
            $_SESSION[$this->key] = array();
        }
        
        $_SESSION[$this->key][$name] = $value;
    }
    
    /**
     *
     * @return string the key used by this container in $_SESSION
     */
    public function getKey() {
        return $this->key;
    }
}
